import uuid
import requests
import json



import base64


import base64
from io import BytesIO
from PIL import Image


def img_to_base64(img):
    """
    将图片对象转换为Base64编码字符串

    :param img: 图片对象（例如通过Pillow库打开的图片对象）
    :return: 图片对应的Base64编码字符串
    """
    try:
        output_buffer = BytesIO()
        img.save(output_buffer, format='PNG')  # 这里将图片保存为PNG格式到内存缓冲区，你也可以根据实际需求换格式
        image_bytes = output_buffer.getvalue()
        base64_encoded = base64.b64encode(image_bytes)
        return base64_encoded.decode('utf-8')
    except Exception as e:
        print(f"转换过程出现错误: {e}")
        return None


def generate_random_id():
    # 生成一个 UUID
    random_uuid = uuid.uuid4()
    # 将 UUID 转换为十六进制字符串并取前 16 位
    return random_uuid.hex[:16]

def ajaxhttp(base64):
    url = "http://127.0.0.1:1224/api/ocr"
    data = {
        "base64": base64,
        # 可选参数示例
        "options": {
            "data.format": "text",
        }
    }
    headers = {"Content-Type": "application/json"}
    data_str = json.dumps(data)
    response = requests.post(url, data=data_str, headers=headers)
    response.raise_for_status()
    res_dict = json.loads(response.text)
    # print(res_dict)
    return res_dict.get('data')

#img
def img2text(img):
    try:
        # 緩存到本地
        # imagepath=f'E:\\auto\\PythonProject1\\testimage\\{generate_random_id()}.png'
        # imagepath = f'E:\\auto\\PythonProject1\\testimage\\a1.png'
        # img.save(imagepath)
        # 使用接口 orc
        base64_1=img_to_base64(img)
        if len(base64_1):
            result1=ajaxhttp(base64_1)
            print('orcinage result1--->', result1)
            return result1
    except Exception as e:
         print('error orc',e)
         return None


if __name__ == '__main__':
    imagepath = f'E:\\auto\\PythonProject1\\testimage\\a1.png'
    _image = Image.open(imagepath)
    img2text(_image)